/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-03-27 11:56:42
 * @LastEditors: DESKTOP-05FP536\Administrator 18368095041@163.com
 * @LastEditTime: 2025-01-15 17:17:30
 * @FilePath: /cdss-admin-web/src/views/system/UsersManage/components/EditView/useForm.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { ref, Ref, watch } from 'vue';
import { useMy, MyInfoParam, PasswordParam } from '@/service/useMy';
import { useRules } from '@/service/useRules';
import { FormInstance } from 'element-plus';
import { message } from '@/utils/message';

export const useForm = (formRef: Ref<FormInstance | undefined>) => {
    const {
        info,
        infoLoading,
        updateMyPassword,
        updateMyInfo,
        getMyInfo,
        updateLoading
    } = useMy();

    const myInfoParam = ref(new MyInfoParam());

    const { requiredRule, mobileRule } = useRules();

    const rules = {
        mobile: [...requiredRule, ...mobileRule],
        name: [...requiredRule]
    };

    const handleSubmit = () => {
        formRef.value?.validate(async (isValid) => {
            if (isValid) {
                await updateMyInfo(myInfoParam.value);
                message('操作成功', 'success');
            }
        });
    };

    const getDetail = async () => {
        formRef.value?.resetFields();
        await getMyInfo();
        myInfoParam.value.name = info.value?.name ?? myInfoParam.value.name;
        myInfoParam.value.mobile =
            info.value?.mobile ?? myInfoParam.value.mobile;
        myInfoParam.value.avatarId =
            info.value?.avatarId ?? myInfoParam.value.avatarId;
        myInfoParam.value.gender =
            info.value?.gender ?? myInfoParam.value.gender;
        myInfoParam.value.email = info.value?.email ?? myInfoParam.value.email;
    };

    getDetail();

    return {
        infoLoading,
        myInfoParam,
        updateLoading,
        handleSubmit,
        rules,
        getDetail
    };
};
